<template>
  <ElDialog :title="title" v-model="isOpen" width="60%" append-to-body @closed="handleBeforeClose">
    <avue-form :option="option" v-model="form" ref="listFormRef" @submit="handleSubmit"> </avue-form>
    <template #footer>
      <el-button type="primary" @click="listFormRef.submit()">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
import { ref, nextTick } from "vue";
import useFormOption from "@/views/system/dict/combination/useFormOption";
import { addType, updateType, getType } from "@/api/system/dict/type";
import type { IOpenFromDialog } from "@/views/commonType/paramsType";
import { ElMessage } from "element-plus";
import { resetForm } from "@/utils/tool";

const defaultData = {
  status: "1",
};

const emit = defineEmits(["done"]);

const ntype = ref("");
const listFormRef = ref();

const option = useFormOption();

const form = ref<any>(defaultData);
const title = ref("新增");
const isOpen = ref(false);

async function handleSubmit(data: any, done: () => void) {
  data.dictData.forEach((item: any, index: any) => {
    item.dictSort = index;
  });
  try {
    if (ntype.value === "add") {
      await addType(data);
    }
    if (ntype.value === "edit") {
      await updateType(data);
    }
    ElMessage.success("操作成功");
    cancel();
    emit("done");
  } catch (err) {}
  done();
}

async function fetchData(id: string) {
  const res = await getType(id);
  form.value = res.data;
}

async function init(params: IOpenFromDialog) {
  form.value = defaultData;
  isOpen.value = true;
  ntype.value = params.type;

  await nextTick();
  if (params.id) {
    fetchData(params.id);
  }
}

function cancel() {
  isOpen.value = false;
}

function handleBeforeClose() {
  resetForm(form, defaultData, listFormRef);
}

defineExpose({
  init,
});
</script>
